package com.yuliang.runner;

import com.yuliang.domain.entity.Article;
import com.yuliang.service.ArticleService;
import com.yuliang.utils.RedisCache;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *  CommandLineRunner实现项目启动时预处理
 */
@Component
public class ViewToRedis implements CommandLineRunner {

    @Resource
    private RedisCache redisCache;
    @Resource
    private ArticleService articleService;


    @Override
    public void run(String... args) throws Exception {
        List<Article> list = articleService.list(null);
        Map<String,Integer> map = new HashMap<>();//key:id value:viewCount
        for (Article article:list) {
            map.put(article.getId().toString(),article.getViewCount().intValue());//1L无法递增，转换成Integer类型
        }
        //存储到redis中
        redisCache.setCacheMap("article:viewCount",map);
    }
}
